package com.atcookie.wc;

import org.apache.flink.api.common.JobExecutionResult;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * 无界流量 读取socket
 * 1创建环境
 * 2.读取数据socket
 * 3.处理数据
 * 4.输出
 * 5.执行
 */
public class WordCountStreamUnbondedDemo {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment environment = StreamExecutionEnvironment.getExecutionEnvironment();
        DataStreamSource<String> dataStreamSource = environment.socketTextStream("hadoop102", 7777);

//        /**
//         * 此处lamb写法会报错。因为存在泛型擦除
//         * InvalidTypesException
//         */
//        SingleOutputStreamOperator<Tuple2<String, Long>> sum = dataStreamSource.flatMap(
//                (String line, Collector<Tuple2<String, Long>> out) -> {
//                    String[] words = line.split(" ");
//
//                    for (String word : words) {
//                        out.collect(Tuple2.of(word, 1L));
//                    }
//                }).returns(Types.TUPLE(Types.STRING, Types.LONG))//此处防止lambda写法的InvalidTypesException，就是可以推断出Tuple2类型，推断不出来Tuple2<String, Long>
//                .keyBy(data -> data.f0)
//                .sum(1);
//

        //3 处理数据:切分 转化 分组 聚合
        SingleOutputStreamOperator<Tuple2<String, Integer>> tuple2SingleOutputStreamOperator = dataStreamSource.flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
            public void flatMap(String s, Collector<Tuple2<String, Integer>> collector) throws Exception {
                //collector 是收集器
                String[] s1 = s.split(" ");
                for (String str : s1) {
                    collector.collect(Tuple2.of(str, 1));
                }
            }
        });


        KeyedStream<Tuple2<String, Integer>, String> tuple2StringKeyedStream = tuple2SingleOutputStreamOperator.keyBy(new KeySelector<Tuple2<String, Integer>, String>() {
            public String getKey(Tuple2<String, Integer> tuple2) throws Exception {
                return tuple2.f0;
            }
        });
        SingleOutputStreamOperator<Tuple2<String, Integer>> sum = tuple2StringKeyedStream.sum(1);
        sum.print();

        JobExecutionResult execute = environment.execute();
    }
}
